<script setup>
import {reactive, ref} from "vue";
import xx from "@/axios/xx";
import { ElMessage, ElMessageBox, ElIcon } from "element-plus";
import {Delete, Edit, Plus, Search} from "@element-plus/icons-vue";

const info = reactive({
  list: [],//列表数据
  searchForm: {
    fullName: '',
    userName: '',
    userType: '',
    start: ''
  },//查询表单数据
  persistForm: {
    userId: '',
    fullName: '',
    email: '',
    phoneNumber: '',
    address: '',
    gender: '',
    avatar: '',
    companyId: '',
    createdAt: '',
    username: '',
    password: '',
    idCard: '',
    creditCard:'',
    creditRank:'',
  },//持久化表单数据
  dialogVisible: false, //对话框数据
  pageNum: 1, //当前页
  pageSize: 5, //每页大小
  total: 0, //总条数
  isAdd: true, //增加和修改标识
  upload:'',
  dialogVisibleImage:false,//详图展示
  dialogImageUrl:'',
})

const ruleFormRef = ref({
});

info.upload = xx.defaults.baseURL+'upload/singleImage'


const validateEMail = (rule, value, callback) => {

  const reg =/^([a-zA-Z0-9]+[-_\.]?)+@[a-zA-Z0-9]+\.[a-z]+$/;
  if(value==''||value==undefined||value==null){
    callback();
  }else{
    if (!reg.test(value)){
      callback(new Error('请输入正确的邮箱地址'));
    } else {
      callback();
    }
  }}


const rules = reactive({
  fullName: [
    { required: true, message: '请输入用户名', trigger: 'blur' }
  ],
  username: [
    { required: true, message: '请输入账号名', trigger: 'blur' }
  ],
  id_card: [
    { required: true, message: '请输入身份证号', trigger: 'blur' }
  ],
  phoneNumber: [
    { required: true, message: '请输入电话', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { validator: validateEMail, trigger: 'blur' }
  ],
})


//查询用户信息
const load = () => {
  xx.get("/userInfo",{
    params: {
      //携带了这些参数作为查询条件。
      pageNum:info.pageNum,
      pageSize:info.pageSize,
      fullName: info.searchForm.fullName,
      userName: info.searchForm.userName,
      start: info.searchForm.start,

    }
  }).then(res =>{
    console.log(res);
    info.list = res.data.list;
    //当前页
    info.pageNum = res.data.pageNum;
    //每页大小
    info.pageSize = res.data.pageSize;
    //总条数
    info.total = res.data.total;
  })
}
load();

const beforeAvatarUpload = (rawfile)=>{
  if(!rawfile.type.startsWith('image/')){
    ElMessage.error("只能上传图片类型")
    return false
  }
  if(rawfile.size/1024/1024>=2){
    ElMessage.error("上传大小限制在2MB")
    return false
  }
  return true
}

const handleAvatarSuccess = (response,upload) =>{
  info.persistForm.avatar = response
}
const viewBigAvatar = (avatar) =>{
  info.dialogImageUrl = avatar
  info.dialogVisibleImage = true;
}

//分页当前页改变
const handleCurrentChange = (pageNum) => {
  //pageNum是前端网页所选择的当前页
  //传递数据给info.pageSize
  info.pageNum = pageNum;
  // 执行加载函数，加载函数会把info.pageNum数据发送给后端，
  // 后端在根据接收到的当前页和每页数据大小返回数据给前端，
  // 前端再用info.pageNum和info.pageSize接收数据
  load();
}
//分页每页数据大小改变
const handleSizeChange = (pageSize) => {
  //pageSize是前端所选择的每页大小
  //传递数据给info.pageSize
  info.pageSize = pageSize;
  // 执行加载函数，加载函数会把info.pageSize数据发送给后端，
  // 后端在根据接收到的当前页和每页数据大小返回数据给前端，
  // 前端再用info.pageNum和info.pageSize接收数据
  load();
}
//删除数据
const handleDelete = (userId) => {
  ElMessageBox.confirm(
      '确定删除该条产品类型信息?',
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
  )
      .then(() => {
        xx.delete("/userInfo/"+userId).then(res => {
          console.log(res);
          if(res.code ==200){
            ElMessage({
              type: 'success',
              message: res.message,
            })
            load();
          } else {
            ElMessage.error(res.message)
          }
        })
      })
      .catch(() => {
        ElMessage({
          type: 'info',
          message: '取消删除',
        })
      })
}
//关闭对话框清除数据
const handleClose = () => {
  info.persistForm = {};
  info.dialogVisible = false;
}
//增加按钮表单显示方法
const add = () => {
  info.dialogVisible = true;
  info.isAdd = true
}
//持久化数据
const persistence = () => {
  if (!ruleFormRef) return
  ruleFormRef.value.validate((valid) => {
    if (valid) {
      xx({
          url:"/userInfo",
          method:info.isAdd?"post":"put",
          data:info.persistForm
        }).then(res => {
          if (res.code == 200){
            ElMessage({
              type: 'success',
              message: res.message,
            })
          } else {
            ElMessage.error(res.message)
          }
        })
      // 关闭对话框
        info.dialogVisible = false;
        //清空数据
        info.persistForm = {}
        //重新加载
        load()
    }
  })

}
//编辑数据
const handleEdit = (userId) => {
  info.isAdd = false;
  xx.get("/userInfo/"+userId).then(res => {
    info.persistForm = res.data;
  })
  info.dialogVisible = true;
}
</script>

<template>
  <!-- 增加按钮 -->
  <el-button type="success" @click="add">
    <!-- 加号图标 -->
    <el-icon class="el-icon--left" ><Plus /></el-icon>增加贷款用户
  </el-button>
  <br><br>
  <!--快捷查询-->
  <el-form :inline="true" :model="info.searchForm" class="demo-form-inline">
    <el-form-item label="贷款人名称：">
      <el-input v-model="info.searchForm.fullName" placeholder="模糊查询" clearable />
    </el-form-item>
    <el-form-item label="贷款人登录账号：">
      <el-input v-model="info.searchForm.userName" placeholder="精准查询" clearable />
    </el-form-item>
    <el-form-item label="创建时间：">
      <el-date-picker
          v-model="info.searchForm.start"
          type="datetime"
          placeholder="开始时间"
          format="YYYY-MM-DD hh:mm:ss"
          value-format="YYYY-MM-DD hh:mm:ss"
      />

    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="load" :icon="Search">快捷查询</el-button>
    </el-form-item>
  </el-form>
  <!--表格信息-->
  <el-table :data="info.list" stripe border  style="width: 100%">
    <el-table-column fixed prop="userId"  align="center" label="序号" width="80" />
    <el-table-column fixed prop="fullName" align="center" label="贷款人名称" width="180" />
    <el-table-column fixed prop="idCard" align="center" label="身份证" width="180" />
    <el-table-column prop="username" align="center" label="账号" width="180" />
    <el-table-column prop="gender" align="center" label="性别" width="80" />
    <el-table-column prop="avatar" label="头像" align="center" width="80">
      <template #default="scope">
        <el-image style="cursor: pointer;height: 50px" :src="scope.row.avatar" @click="viewBigAvatar(scope.row.avatar)"></el-image>
      </template>
    </el-table-column>
    <!--<el-table-column prop="userType" align="center" label="贷款类型" width="120" />-->
    <!--<el-table-column prop="companyId" align="center" label="所属单位" width="180" />-->
    <el-table-column prop="email" align="center" label="邮箱" width="210" />
    <el-table-column prop="phoneNumber" align="center" label="联系方式" width="180" />
    <el-table-column prop="address" align="center" label="地址" width="180" />
    <el-table-column prop="createdAt" align="center" label="创建时间" width="180" />
    <el-table-column fixed="right" label="操作" align="center" width="220" >
      <template #default="scope">
        <el-button size="small" style="background-color: bisque" @click="handleEdit(scope.row.userId)"><el-icon class="el-icon--left" ><Edit /></el-icon>
          修改 </el-button>
        <el-button size="small" type="danger" @click="handleDelete(scope.row.userId)"><el-icon class="el-icon--left"  ><Delete /></el-icon>
          删除 </el-button>
      </template>
    </el-table-column>
  </el-table>
  <!--分页-->
  <br>
  <el-pagination
      v-model:current-page="info.pageNum"
      v-model:page-size="info.pageSize"
      :page-sizes="[5, 10, 15, 20]"
      :small="false"
      :disabled="false"
      :background="true"
      layout="total, sizes, prev, pager, next, jumper"
      :total="info.total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
  />
  <!--窗口-->
  <el-dialog
      v-model="info.dialogVisible"
      :title="info.isAdd ? '添加用户信息':'修改用户信息'"
      width="50%"
      :before-close="handleClose"
  >
    <el-form :rules=rules ref="ruleFormRef" :model="info.persistForm" label-width="auto" style="max-width: 90%;margin-left: 20px">
      <el-form-item label="贷款人名称" prop="fullName">
        <el-input v-model="info.persistForm.fullName" style="width: 196.4px"/>
      </el-form-item>
      <el-row>
        <el-form-item label="账号" prop="username">
          <el-input v-model="info.persistForm.username" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="info.persistForm.password"  type="password"/>
        </el-form-item>
      </el-row>
      <el-row>
        <el-form-item label="头像">
          <el-upload
              class="avatar-uploader"
              :action="info.upload"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
          >
            <img v-if="info.persistForm.avatar" :src="info.persistForm.avatar" class="avatar"  alt="头像"/>
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
      </el-row>

      <el-form-item label="性别" prop="gender">
        <el-radio-group v-model="info.persistForm.gender">
          <el-radio value="男">男</el-radio>
          <el-radio value="女">女</el-radio>
          <!--<el-radio value="其他">其他</el-radio>-->
        </el-radio-group>
      </el-form-item>

      <el-row>

        <el-form-item label="年龄" prop="age">
          <el-input v-model.number="info.persistForm.age" placeholder="请输入年龄" />
        </el-form-item>

        <!-- 添加身份证号输入框 -->
        <el-form-item label="身份证号" prop="idCard">
          <el-input v-model="info.persistForm.idCard" placeholder="请输入身份证号" />
        </el-form-item>

        <!-- 添加信用卡号输入框 -->
        <el-form-item label="信用卡号" prop="creditCard">
          <el-input v-model="info.persistForm.creditCard" placeholder="请输入信用卡号" />
        </el-form-item>

        <el-form-item label="信誉等级" prop="creditRank">
          <el-radio-group v-model="info.persistForm.creditRank">
            <el-radio label="优">优</el-radio>
            <el-radio label="良">良</el-radio>
            <el-radio label="中">中</el-radio>
            <el-radio label="差">差</el-radio>
            <el-radio label="劣">劣</el-radio>
          </el-radio-group>
        </el-form-item>

        <!-- 原有输入项保持不变 -->
        <el-form-item label="联系方式" prop="phoneNumber" >
          <el-input v-model="info.persistForm.phoneNumber" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="info.persistForm.email" />
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input type="textarea" v-model="info.persistForm.address" />
        </el-form-item>
      </el-row>

      <el-row>
        <el-form-item label="创建时间">
          <el-date-picker
              v-model="info.persistForm.createdAt"
              type="datetime"
              placeholder="选择时间"
              format="YYYY-MM-DD hh:mm:ss"
              value-format="YYYY-MM-DD hh:mm:ss"
          />
        </el-form-item>
      </el-row>
      <el-row>


      </el-row>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="persistence">
          保存信息
        </el-button>
      </div>
    </template>
  </el-dialog>


  <el-dialog v-model="info.dialogVisibleImage">
    <img :src="info.dialogImageUrl" style="width: 100%" alt="Preview Image">
  </el-dialog>
</template>

<style scoped>
/*pagination分页组件居中显示*/
#pagination{
  justify-content: center;
}
.el-form-item{
  margin-left: 40px;
}
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
  border: 1px solid #666;
}
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
  border: 1px solid #DCDFE6FF;
}
</style>